package com.dotflat.refund.service.impl;

import com.dotflat.fin.PO.RefundRecordItemPO;
import com.dotflat.fin.domain.RefundRecord;
import com.dotflat.refund.PO.RefundRecordPO;
import com.dotflat.refund.domain.RefundRecordItem;
import com.dotflat.refund.repository.RefundRecordRepository;
import com.dotflat.refund.service.RefundRecordItemService;
import com.dotflat.refund.service.RefundRecordService;
import com.dotflat.rest.PO.AreableObjectBasePO;
import com.dotflat.rest.service.impl.AreableObjectBaseServiceImpl;
import com.matt.commons.exception.BusinessException;
import com.matt.foundation.model.ErrorCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;
import java.util.function.Consumer;

/**
 * 订单信息service
 *
 * @author ：Ron
 * @date ：Created in 2020/10/30 13:06
 */
@Service
public class RefundRecordServiceImpl extends AreableObjectBaseServiceImpl<RefundRecord, RefundRecordRepository> implements RefundRecordService {

    @Override
    @Autowired
    public void setBaseRepository(RefundRecordRepository baseRepository) {
        super.setBaseRepository(baseRepository);
    }

    @Autowired
    private RefundRecordItemService itemService;

    @Override
    @Transactional(rollbackOn = Exception.class)
    public RefundRecord add(String areaId, String staffId, AreableObjectBasePO po, Consumer<? super RefundRecord> preAction) {

        RefundRecordPO param = null;
        if (po instanceof RefundRecordPO){
            param = (RefundRecordPO) po;
        }else{
            return super.add(areaId, staffId, po, preAction);
        }

        List<RefundRecordItemPO> items = param.getItems();

        if (items == null || items.size() == 0){
            throw new BusinessException(ErrorCode.PRODUCT_NOT_EXIST, "必须指定退款产品");
        }

        param.setItems(null);

        //需要计算总价格
        Long fullAmount = 0L;
        for (RefundRecordItemPO i : items){
            fullAmount += i.getRefundAmount();
        }

        param.setRefundMoney(fullAmount);

        RefundRecord ret = super.add(areaId, staffId, param, preAction);

        List<RefundRecordItem> ri = itemService.addAll(areaId, staffId, items, (item)->{
            item.setRecordId(ret.getId());
        });

        ret.setItems(ri);


        return ret;
    }
}
